import PackV1 from "../../base/net/chatpackv1.js"

import * as fun from "../../core/fun.js"

const 默认服务器地址 = 'ws://127.0.0.1:3000/';
const KEY前缀 = "HYL_CQC_"
/**
 ws框架与token无关
 token是连接后的上层行为
 */
let WsClient = {
	c当前用户: null,
	wsURL: 默认服务器地址,
	newClient: function() {
		let that = this;
		/**
		 * 必须使用f接收委托= 自定义函数(res)
		 * 才能工作
		 */
		let self = {};
		self.f接收委托 = {};
		let socketOpen = false;
		let sendQueue = [];
		let _socket = null;

		return new Promise(function(resolve, reject) {
			let msg = '';
			that.wsURL = that.wsURL || 默认服务器地址;
			try {
				_socket = uni.connectSocket({
					url: that.wsURL,
					success(e) {
						msg = "能连接ws服务端..." + that.wsURL;
						console.log(msg);
					},
					fail(e) {
						msg = that.wsURL + "ws服务器关闭无法连接...";
						console.log(msg, JSON.stringify(e));
						reject(msg);
					}
				});
				//socket.send()
				// uni.onSocketOpen(function(res) {
				// 	console.log('WebSocket连接已打开！', res);
				// });
				//
				_socket.onOpen(function(result) {
					socketOpen = true;
					// for (var i = 0; i < sendQueue.length; i++) {
					// 	_socket.send({
					// 		data: sendQueue[i]
					// 	});
					// }
					// sendQueue = [];
					
					console.log("连接ws服务端成功!");
					resolve(self);
				});

				_socket.onError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
				});

				//uni.onSocketMessage(function(res) {这种写法最大的问题是 只对当前的socket有效,
				_socket.onMessage(function(res) {

					//string 可以是文本也可以是jsonstring, 
					//在 packv1协议中基本不用
					if (fun._IS.isString(res.data)) {
						console.log('收到服务器测试文本：', Object.prototype.toString.call(res.data), res
							.data);
						//self.f接收委托(res.data);
					} else { // isbuffer 二进制 自定义协议 PackV1
						let data = new Uint8Array(res.data);
						let pv = PackV1.deserial(data);
						//let obj2=bfun.bytes2Json(data);

						if (self.f接收委托.hasOwnProperty(pv.指令)) {
							try {
								//console.log('收到服务器内容-------：', pv);
								self.f接收委托[pv.指令](pv);
							} catch (e) {
								console.log("委托处理11", pv.指令, e)
							}
						}
						// Object.values(self.f接收委托).forEach((handler) => {
						// 	handler(pv);
						// });
					}

				})

				_socket.onClose(function(res) {
					//console.log('WebSocket 已关闭！', res);
					_socket = null;
					reject('WebSocket 已关闭！');
				});
				//self.ws=_socket;
			} catch (err) {
				console.log("创建 ws 异常", err)
			}
			if (_socket == null) return;

			self.send = function(pack) {
				if (socketOpen) {
					_socket.send({
						data: pack
					});
				} else {
					sendQueue.push(pack);
				}
			};
			/**
			 * @param {Object} packv1
			 */
			self.sendPackv1 = function(packv1) {
				if (packv1)
					self.send(PackV1.serial(packv1))
			};
			self.sendCmd = function(类型) {
				let pv = new PackV1();
				pv.指令 = 类型;
				self.sendPackv1(pv);
			};
			self.sendString = function(类型, 数据) {
				let pv = new PackV1();
				pv.指令 = 类型;
				if (数据) pv.指令参数 = 数据
				self.sendPackv1(pv);
			};
			self.sendBuffer = function(类型, 参数, 二进制流) {
				let pv = new PackV1();
				pv.指令 = 类型;
				if (参数) pv.指令参数 = JSON.stringify(参数)
				if (二进制流) pv.字节数据 = 二进制流
				self.sendPackv1(pv);

			};
			self.sendJson = function(类型, 参数) {
				let pv = new PackV1();
				pv.指令 = 类型;
				if (参数) pv.指令参数 = JSON.stringify(参数)
				self.sendPackv1(pv);

			};

		});

	},
	getkeys() {
		let arr = []
		for (let k in this.m用户集)
			arr.push(k)
		return arr;
	},
	removeClient() {
		try {
			this.c当前用户 = null;
		} catch (e) {}
	},
	delClient(uid) {
		try {
			this.c当前用户 = null;
			uni.removeStorageSync('se_' + uid, null);
		} catch (e) {}
	},
	/**
	 * 获取或者新建客户端容器 (包含了客户端会话,处理句柄和收发数据组件)
	 */
	getClient() {
		if (this.c当前用户 != null) return this.c当前用户;
		let that = this;
		let tmp = {};
		let p = new Promise(function(resolve, reject) {
			//console.log("getClient: 11");
			//消息缓存
			//tmp.mq = Tmq.newCreate();
			//设置新的网络连接

			//console.log("tmp.ws ",tmp.ws )
			/**
			 * 设置接收委托函数
			 * @param {Object} cmd
			 * @param {Object} handler
			 */
			tmp.putHandler = function(cmd, handler) {
				//console.log(tmp,tmp.ws,cmd,handler)
				if (tmp.ws)
					tmp.ws.f接收委托[cmd] = handler;
			}

			tmp.session = {};
			/**
			 * 保存当前用户会话属性
			 */
			tmp.saveStore = function(key,str) {
				key=KEY前缀+key;		
				try {
					//let str = JSON.stringify(this.session);
					//console.log("wsclient.saveSession",str)
					uni.setStorageSync(key, str);
				} catch (e) {}
				
			};
			tmp.removeStore = function(key) {
				key=KEY前缀+key;
				try {
					uni.removeStorageSync(key);
				} catch (e) {
					// error
				}
			}
			/**
			 * 从store中读取缓存当前用户信息
			 * 返回true 表示读取到本地的store 中的token和uid
			 * false 表示无法读取到本地的store
			 * @param {Object} uid
			 */
			tmp.loadStore = function(key) {
				key=KEY前缀+key;
				return uni.getStorageSync(key);				
			};
			that.newClient().then(v => {
				tmp.ws = v;
				resolve(tmp);
			}, err => {
				//console.log("异常:",err)
				reject(err);
			});


			that.c当前用户 = tmp;
		});
		return p;
		//console.log("----tmp: ",tmp);
		//return tmp;
	}
}

export default WsClient;
